<?php

//This file may be called directly with the tiempoint and the password set as parameters in the url, or included at the end of another file after the $timepoint variable has been set.

ini_set("memory_limit", "150M");
ini_set("max_execution_time", 120);

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');

require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');

if ($_GET["pass"] != SCRIPT_PWD) die("Incorrect password");
	
if (isset($_GET['date'])) {
	if (preg_match("/^[0-9]{4,4}[-][0-9]{2,2}[-][0-9]{2,2}$/", $_GET['date'])) {
		$timepoint = $_GET['date'];
	}
	else die("Date must be of form YYYY-MM-DD");
}
else die("Date must be set!");

$db = new DB();
$connection = $db->connect();
if ($stmt = $connection->prepare('INSERT INTO `hdates` (`date`) VALUES (?)')){
	$stmt->bind_param('s', $timepoint);
	$stmt->execute();
	$stmt->close();
}
else{
	die("Statement failed3");
}
$db->disconnect();

$dbcountry = new DBCountry();
$dbdivision = new DBDivision();
$countries = $dbcountry->getCountries();
$bots=array();
$supporters;
$numdivisions;
$divsize=array(0,1,4,16,64,256,1024,1024,2048,2048,4096,4096,4096,4096,4096,4096,4096);
foreach ($countries as $country){
	$bots[$country->getCountryID()]=array();
	$divisions = $dbdivision->getDivisionsByCountry($country, true);
	$numdivisions[$country->getCountryID()]=$divisions->count();
	for($a=1;$divisions->count()>=$a;$a++){
		$bots[$country->getCountryID()][$a]=array();
		for($b=1;$divsize[$a]>=$b;$b++){
			$bots[$country->getCountryID()][$a][$b]=9;
			$supporters[$country->getCountryID()][$a][$b]=9;
		}
	}
}

$numfetched=0;
$leagueID=0;

$firstname=array();

$db = new DB();
$connection = $db->connect();
		
if ($stmt = $connection->prepare('SELECT `league#`, `name`, `country#`, `division#` FROM `tleague`')) {
	$stmt->execute();
	$stmt->bind_result($leagueID, $name, $countryID, $level);

	while ($stmt->fetch()) {
		$numfetched++;
		$leaguecountry[$leagueID]=$countryID;
		$leaguelevel[$leagueID]=$level;
		if($level==1){
			$leagueleague[$leagueID]=1;
			$firstname[$countryID]=$name;
		}
		else{
			strtok($name,".");
			$leagueleague[$leagueID]=strtok(".");
			if(22>$leagueID){ //Sweden fix
				$leagueleague[$leagueID]=$leagueID-5;
				if(6>$leagueID){
					$leagueleague[$leagueID]=$leagueID-1;
				}
			}
		}
	}			
	$stmt->close();
}

$db->disconnect();
$db = new DB();
$connection = $db->connect();

$numfetched2=0;
if ($stmt = $connection->prepare("SELECT `league#`, `bots`, `supporters` FROM `hleague` WHERE `date#` = ?")) {
	$stmt->bind_param('s',$timepoint);
	$stmt->execute();
	$stmt->bind_result($leagueID, $numsupporters, $numbots); //Quick'n'dirty part, $bots now really contain supporter info and vice versa

	while ($stmt->fetch()) {
		$numfetched2++;
		$bots[$leaguecountry[$leagueID]][$leaguelevel[$leagueID]][$leagueleague[$leagueID]]=8-$numbots;
		$supporters[$leaguecountry[$leagueID]][$leaguelevel[$leagueID]][$leagueleague[$leagueID]]=8-$numsupporters;
	}
	$stmt->close();
}
else{
	die("Statement failed");
}

$db->disconnect();

$xres=array(0,256,128,64,32,16,8,8,8,8,4,4,4,4,4,4,4);
$yres=array(0,256,128,64,32,16,8,8,4,4,4,4,4,4,4,4,4);
$xstart=array(0,0,256,512,768,0,256,512,768,0,256,512,768,0,256,512,768);
$ystart=array(0,0,0,0,0,256,256,256,256,512,512,512,512,768,768,768,768);
$base65=str_split("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#|_");

$missingdata=array();

$db = new DB();
$connection = $db->connect();
if ($stmt = $connection->prepare('INSERT INTO `hsbarstrings` (`country`,`date`,`string`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `string`=VALUES(`string`)')){
	$stmt->bind_param('iss', $a, $timepoint, $datastring);
}
else{
	die("Statement failed 2");
}

for($a=1;256>=$a;$a++){
	if($numdivisions[$a]){
		if($numdivisions[$a]>12){
			$im = imagecreate(1024,1024);
		}
		elseif($numdivisions[$a]>8){
			$im = imagecreate(1024,768);
		}
		elseif($numdivisions[$a]>4){
			$im = imagecreate(1024,512);
		}
		elseif($numdivisions[$a]==4){
			$im = imagecreate(1024,256);
		}
		else{
			$im = imagecreate(768,256);
		}
		$colours[9]=imagecolorallocate($im, 128, 128, 128);
		$colours[8]=imagecolorallocate($im, 232, 232, 232);
		$colours[7]=imagecolorallocate($im, 255, 0, 255);
		$colours[6]=imagecolorallocate($im, 255, 0, 0);
		$colours[5]=imagecolorallocate($im, 255, 144, 0);
		$colours[4]=imagecolorallocate($im, 255, 255, 0);
		$colours[3]=imagecolorallocate($im, 0, 192, 192);
		$colours[2]=imagecolorallocate($im, 0, 160, 0);
		$colours[1]=imagecolorallocate($im, 0, 0, 192);
		$colours[0]=imagecolorallocate($im, 0, 0, 0);
		$botcount=array();
		$datastring="";
		for($b=1;$numdivisions[$a]>=$b;$b++){
			$botcount[$b]=array();
			$x=0;
			$y=0;
			for($c=1;$divsize[$b]>=$c;$c++){
				if($bots[$a][$b][$c]==9){
					$missingdata[$a]=1;
				}
				else{
					$botcount[$b][8-$bots[$a][$b][$c]]++;
					$botcount[$b][9]+=$supporters[$a][$b][$c];
				}
				imagefilledrectangle($im,$xstart[$b]+$x,$ystart[$b]+$y,$xstart[$b]+$x+$xres[$b]-1,$ystart[$b]+$y+$yres[$b]-1,$colours[$bots[$a][$b][$c]]);
				$x=($x+$xres[$b])%256;
				if($x==0){
					$y+=$yres[$b];
				}
			}
			for($c=0;9>$c;$c++){
				$lsb=$botcount[$b][$c]%65;
				$msb=($botcount[$b][$c]-$lsb)/65;
				$datastring.=$base65[$msb].$base65[$lsb];
			}
			$lsb=$botcount[$b][9]%65;
			$msb=(($botcount[$b][9]-$lsb)/65)%65;
			$vmsb=(($botcount[$b][9]-$lsb-$msb*65)/65/65);
			$datastring.=$base65[$vmsb].$base65[$msb].$base65[$lsb];
		}
		imagepng($im,SITE_ROOT."botmap/s".$a."-".$timepoint.".png");
		imagedestroy($im);
		$stmt->execute();
	}
}
$stmt->close();
$db->disconnect();



$numdates=0;
$db = new DB();
$connection = $db->connect();

$datearray=array();
$timepointstr="";
$commachar="";
		
if ($stmt = $connection->prepare('SELECT `date` FROM `hdates` ORDER BY `date` ASC')) {
	$stmt->execute();
	$stmt->bind_result($datefetched);

	while ($stmt->fetch()) {
		$datearray[]=$datefetched;
		$numdates++;
		$timepointstr.=$commachar.'"'.$datefetched.'"';
		$commachar=',';
	}
	$stmt->close();
}
else{
	die("Statement failed");
}
$db->disconnect();



$db = new DB();
$connection = $db->connect();

if ($stmt = $connection->prepare("SELECT `string` FROM `hsbarstrings` WHERE `country` = ? AND `date` = ?")) {
	$stmt->bind_param('is',$a,$date);
	$stmt->bind_result($stringfetched);
}
else{
	die("Statement failed 4 ");
}

for($a=1;256>=$a;$a++){
	if($numdivisions[$a]){
		$barstring="";
		foreach($datearray as $date){
			$stmt->execute();
			$stmt->fetch();
			while($numdivisions[$a]*21>strlen($stringfetched)){
				$stringfetched.="000000000000000000000";
			}
			$barstring.=$stringfetched;
		}
		$file=fopen(SITE_ROOT."botmap/s".$a.".data","w");
		fwrite($file,"leagueid=$a;firstname='$firstname[$a]';divisions=$numdivisions[$a];timepoints=$numdates;timename=new Array($timepointstr);makepage('$barstring');");
		fclose($file);
	}
	if($missingdata[$a]==1){
		echo "Data for county $a missing<br>";
	}
}

$stmt->close();
$db->disconnect();

echo $numfetched;
echo "<br>";
echo $numfetched2;
?>